package com.iotechn.unimall.admin.api.enterprise;

import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.component.CacheComponent;
import com.iotechn.unimall.data.domain.EnterpriseDO;
import com.iotechn.unimall.data.mapper.EnterpriseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;


@Service
public class AdminEnterpriseServiceImpl implements AdminEnterpriseService {

    private static final String ENTERPRISE_INFO = "CA_ENTERPRISE_INFO";

    @Autowired
    private EnterpriseMapper enterpriseMapper;
    @Autowired
    private CacheComponent cacheComponent;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EnterpriseDO create(EnterpriseDO enterpriseDO, Long adminId) throws ServiceException {
        if (enterpriseMapper.insert(enterpriseDO) > 0) {
            enterpriseDO.setId(enterpriseDO.getId());
            cacheComponent.putRaw(ENTERPRISE_INFO,enterpriseDO.getInfo());
            return enterpriseDO;
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String update(EnterpriseDO enterpriseDO, Long adminId) throws ServiceException {
        if (enterpriseMapper.updateById(enterpriseDO) > 0) {
            cacheComponent.putRaw(ENTERPRISE_INFO,enterpriseDO.getInfo());
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }

    @Override
    public EnterpriseDO detail(Long adminId) throws ServiceException {
        EnterpriseDO enterpriseDO = enterpriseMapper.selectById(1);
        return enterpriseDO;
    }

    @PostConstruct
    public void init(){
        EnterpriseDO enterpriseDO = enterpriseMapper.selectById(1);
        if(enterpriseDO != null){
            cacheComponent.putRaw(ENTERPRISE_INFO,enterpriseDO.getInfo());
        }
    }

}
